package com.hm.hall.commons.util;

import com.hm.hall.commons.config.MyConnection;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author leijianjun
 */
public class MyDbUtils {

    private static Logger log = Logger.getLogger(MyDbUtils.class);

    public static Connection getConnection(String driver, String url, String user, String password) {
        try {
            Class.forName(driver);  //加载驱动程序
            return DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException e) {
            log.error("Sorry,can`t find the Driver!");
            e.printStackTrace();
        } catch (SQLException e) {
            log.error("SQLException !" + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    //******************************************************************************
    public static Object executeUpdate(String sql, Connection con) {
        int result = 0;
        //遍历查询结果集
        try {
            if (con.isClosed()) {
                log.error("data base connection error!!!");
            }
            //2.创建statement类对象，用来执行SQL语句！！
            Statement statement = con.createStatement();
            //3.ResultSet类，用来存放获取的结果集！！
            result = statement.executeUpdate(sql);
            con.close();
        } catch (SQLException e) {
            log.error("SQLException !" + e.getMessage());
            //数据库连接失败异常处理
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static Object executeQuery(String sql, ExecuteQuery execQuery) {
        return executeQuery(sql, execQuery, MyConnection.getConnection());
    }


    public static Object executeQuery(String sql, ExecuteQuery execQuery, Connection con) {
        Object result = null;
        //遍历查询结果集
        try {
            //1 DriverManager.getConnection()方法，连接MySQL数据库！！

            if (con.isClosed()) {
                log.error("data base connection error!!!");
            }
            //2.创建statement类对象，用来执行SQL语句！！
            Statement statement = con.createStatement();
            //3.ResultSet类，用来存放获取的结果集！！
            ResultSet rs = statement.executeQuery(sql);

            result = execQuery.executeQuery(rs);
            rs.close();
            con.close();
        } catch (SQLException e) {
            log.error("SQLException !" + e.getMessage());
            //数据库连接失败异常处理
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    @SuppressWarnings("unchecked")
    public static List<Map<String, Object>> executeQuery(String sql, Connection con) {
        return (List) executeQuery(sql, new ExecuteQuery() {
            @Override
            public Object executeQuery(ResultSet rs) throws SQLException, UnsupportedEncodingException {
                List<Map<String, Object>> datas = new ArrayList<>();
                while (rs.next()) {
                    ResultSetMetaData md = rs.getMetaData();
                    Map<String, Object> data = new HashMap<String, Object>();
                    for (int i = 0; i < md.getColumnCount(); i++) {
                        String cName = md.getColumnName(i + 1);
                        data.put(cName, rs.getObject(cName));
                    }
                    datas.add(data);
                }
                return datas;
            }
        }, con);
    }

    public interface ExecuteQuery {
        Object executeQuery(ResultSet rs) throws SQLException, UnsupportedEncodingException;
    }

    public interface ExecuteQueryResMap {
        Object executeQuery(List<Map<String, Object>> datas) throws SQLException, UnsupportedEncodingException;
    }


}

